package com.xincheng.shuimalong.activity;

import android.content.Intent;
import android.net.Uri;
import android.support.annotation.IdRes;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.xincheng.library.manager.ExitManager;
import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.xlog.XLog;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.GetParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.AppConfig;
import com.xincheng.shuimalong.common.Constant;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.dialog.CheckUpdateDialog;
import com.xincheng.shuimalong.entity.config.CommonConfig;
import com.xincheng.shuimalong.entity.config.RegionData;
import com.xincheng.shuimalong.entity.friend.ImToken;
import com.xincheng.shuimalong.fragment.HomeFragment;
import com.xincheng.shuimalong.fragment.InsuranceFragment;
import com.xincheng.shuimalong.fragment.MarketFragment;
import com.xincheng.shuimalong.fragment.MyselfFragment;
import com.xincheng.shuimalong.util.GreenUtil;
import com.xincheng.shuimalong.util.GsonUtil;
import com.xincheng.shuimalong.util.RongUtil;

import java.util.Map;

import butterknife.BindView;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;


public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.home_menu_point)
    TextView homeMenuPoint;
    @BindView(R.id.care_menu_point)
    TextView careMenuPoint;
    @BindView(R.id.study_menu_point)
    TextView studyMenuPoint;
    @BindView(R.id.my_detail_point)
    ImageView myDetailPoint;

    HomeFragment homeFragment; //首页
    InsuranceFragment insuranceFragment;//保友页面
    MarketFragment marketFragment;//市场页面
    MyselfFragment myselfFragment;//我的

    private ConfigCallBack configCallBack;
    private OrderCallBack orderCallBack;
    private UserInfoCallBack userInfoCallBack;
    private HistoryCallBack historyCallBack;
    private GroupCallBack groupCallBack;
    private long mExitTime = 0;

    private int provinceId = 0;
    private int cityId = 0;
    private int marketCityId = 0;
    private int marketProvinceId = 0;

    public int getProvinceId() {
        return provinceId;
    }

    public void setProvinceId(int provinceId) {
        this.provinceId = provinceId;
    }

    public int getCityId() {
        return cityId;
    }

    public void setCityId(int cityId) {
        this.cityId = cityId;
    }

    public int getMarketCityId() {
        return marketCityId;
    }

    public void setMarketCityId(int marketCityId) {
        this.marketCityId = marketCityId;
    }

    public int getMarketProvinceId() {
        return marketProvinceId;
    }

    public void setMarketProvinceId(int marketProvinceId) {
        this.marketProvinceId = marketProvinceId;
    }

    public void registerGroupCallBack(GroupCallBack groupCallBack) {
        this.groupCallBack = groupCallBack;
    }

    public void registerConfigCallBack(ConfigCallBack configCallBack) {
        this.configCallBack = configCallBack;
    }

    public void registerOrderCallBack(OrderCallBack orderCallBack) {
        this.orderCallBack = orderCallBack;
    }

    public void registerUserInfoCallBack(UserInfoCallBack userInfoCallBack) {
        this.userInfoCallBack = userInfoCallBack;
    }

    public void registerHistoryCallBack(HistoryCallBack callBack) {
        this.historyCallBack = callBack;
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    public void initData() {
        setDefaultFragment();
        ExitManager.getInstance().clearActivies();
        ExitManager.getInstance().addActivity(this);
        GreenUtil.getInstances().setDatabase(this);
        getImToken();
    }

    public OrderCallBack getOrderCallBack() {
        return orderCallBack;
    }

    @Override
    public void addListener() {
        radioGroup.setOnCheckedChangeListener(this);
    }

    private void setDefaultFragment() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        homeFragment = new HomeFragment();
        transaction.replace(R.id.main_fragment, homeFragment);
        transaction.commit();
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
        FragmentManager fm = getSupportFragmentManager();
        // 开启Fragment事务
        FragmentTransaction transaction = fm.beginTransaction();
        switch (i) {
            case R.id.home_menu:
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                }
                transaction.replace(R.id.main_fragment, homeFragment);
                break;
            case R.id.radio_market:
                if (marketFragment == null) {
                    marketFragment = new MarketFragment();
                }
                transaction.replace(R.id.main_fragment, marketFragment);
                break;
            case R.id.radio_insurance:
                if (insuranceFragment == null) {
                    insuranceFragment = new InsuranceFragment();
                }
                transaction.replace(R.id.main_fragment, insuranceFragment);
                break;
            case R.id.radio_myself:
                if (myselfFragment == null) {
                    myselfFragment = new MyselfFragment();
                }
                transaction.replace(R.id.main_fragment, myselfFragment);
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        XLog.e(requestCode + "==" + resultCode);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCodeKey.GO_CITY_SELECT:
                    RegionData province = data.getParcelableExtra(IntentKey.PROVINCE);
                    RegionData city = data.getParcelableExtra(IntentKey.CITY);
                    CommonConfig hotCity = data.getParcelableExtra(IntentKey.HOT_CITY);
                    XLog.e("province->" + province + ",city->" + city + ",hotcity->" + hotCity);
                    if (configCallBack != null) {
                        configCallBack.parseCity(province, city, hotCity);
                    }
                    break;
                case RequestCodeKey.GO_MARKET_FILTER:
                    boolean showNewCar = data.getBooleanExtra(IntentKey.SHOW_NEW_CAR, false);
                    int newCarId = data.getIntExtra(IntentKey.NEW_CAR_ID, 0);
                    int min = data.getIntExtra(IntentKey.MIN, getResources().getInteger(R.integer.range_min_default));
                    int max = data.getIntExtra(IntentKey.MAX, getResources().getInteger(R.integer.range_max_default));
                    int useAge = data.getIntExtra(IntentKey.USE_AGE, 0);
                    if (configCallBack != null) {
                        configCallBack.parseFilter(showNewCar, newCarId, min, max, useAge);
                    }
                    break;
                case RequestCodeKey.GO_INSURANCE_COMPAY_SELECT:
                    CommonConfig company = data.getParcelableExtra(IntentKey.INSURANCE_COMPANY);
                    if (configCallBack != null) {
                        configCallBack.parseCompany(company);
                    }
                    break;
                case RequestCodeKey.GO_RECEIPT_QUOTE:
                    XLog.e("报价成功！");
                    boolean flag = data.getBooleanExtra(IntentKey.QUOTE_SUCCESS, false);
                    if (flag && orderCallBack != null) {
                        orderCallBack.quoteSuccess();
                    }
                    boolean flag2 = data.getBooleanExtra(IntentKey.REFUSE_SUCCESS, false);
                    if (flag2 && orderCallBack != null) {
                        orderCallBack.refuseSuccess();
                    }
                    break;
                case RequestCodeKey.GO_REPUBISH_BILL:
                    boolean flag1 = data.getBooleanExtra(IntentKey.REPUBLISH_SUCCESS, false);
                    if (flag1 && orderCallBack != null) {
                        orderCallBack.republishSuccess();
                    }
                    break;
                case RequestCodeKey.GO_UPDATE_NICKNAME:
                    if (data != null) {
                        String nickName = data.getStringExtra(IntentKey.NICK_NAME);
                        if (userInfoCallBack != null) {
                            userInfoCallBack.changeNickName(nickName);
                        }
                    }
                    break;
                case RequestCodeKey.GO_SEARCH:
                    String keyword = data.getStringExtra(IntentKey.KEYWORD);
                    if (configCallBack != null) {
                        configCallBack.parseKeyWord(keyword);
                    }
                    break;
                case RequestCodeKey.GO_RECEIPT_ISSUE:
                    flag = data.getBooleanExtra(IntentKey.ISSUE_SUCCESS, false);
                    if (flag && orderCallBack != null) {
                        orderCallBack.issueSuccess();
                    }
                    break;
                case RequestCodeKey.GO_SIGN_RECEIVE:
                    flag = data.getBooleanExtra(IntentKey.SIGN_RECEIVE_SUCCESS, false);
                    if (flag && orderCallBack != null) {
                        orderCallBack.signReceiveSuccess();
                    }
                    break;
                case RequestCodeKey.UP_FRIEND_LIST:
                    if (historyCallBack != null) {
                        historyCallBack.loadHistory();
                    }
                    break;
                case RequestCodeKey.UP_GROUPLIST:
                    if (groupCallBack != null) {
                        groupCallBack.loadGroup();
                    }
                    break;
                case RequestCodeKey.GO_PAY:
                    flag = data.getBooleanExtra(IntentKey.PAY_SUCCESS, false);
                    if (flag && orderCallBack != null) {
                        orderCallBack.paySuccess();
                    }
                    break;
                case RequestCodeKey.EVALUATE:
                    flag = data.getBooleanExtra(IntentKey.EVALUATE, false);
                    if (flag && orderCallBack != null) {
                        orderCallBack.evalueteSucess();
                    }
                    break;
                case RequestCodeKey.GO_DESPOSE:
                    flag = data.getBooleanExtra(IntentKey.WITHDRAW_SUCCESS, false);
                    XLog.e("flag->" + flag);
                    if (flag && userInfoCallBack != null) {
                        userInfoCallBack.withdrawSuccess();
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public interface ConfigCallBack {
        void parseCity(RegionData province, RegionData city, CommonConfig hotCity);

        void parseFilter(boolean showNewCar, int newCarId, int min, int max, int useAge);

        void parseCompany(CommonConfig company);

        void parseKeyWord(String keyword);

    }

    public interface HistoryCallBack {
        void loadHistory();
    }

    public interface GroupCallBack {
        void loadGroup();
    }

    public interface OrderCallBack {
        void quoteSuccess();

        void issueSuccess();

        void signReceiveSuccess();

        void paySuccess();

        void evalueteSucess();

        void refuseSuccess();

        void republishSuccess();
    }

    public interface UserInfoCallBack {
        void changeNickName(String nickName);

        void withdrawSuccess();
    }


    private void getImToken() {
        Map<String, String> map = GetParam.getImToken(PrefUtil.getString(getContext(), PrefKey.TOKEN, ""));
        RetroSubscrube.getInstance().getSubscrube(map, new BaseObserver(getContext()) {
            @Override
            protected void onHandleSuccess(Object data, String msg) {
                ImToken imToken = GsonUtil.parseData(data, ImToken.class);
                XLog.e("token获取成功..." + imToken);
                PrefUtil.putString(getContext(), PrefKey.IM_TOKEN, imToken.getToken());
                imConnect();
            }
        });
//        RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {
//            @Override
//            public UserInfo getUserInfo(String s) {
//                return UserInfo();
//            }
//        },true);

    }

    private void imConnect() {
        XLog.e("开始连接IM服务器...");
        if (RongUtil.getInstances().isCurrentProcess(this)) {
            RongIM.connect(PrefUtil.getString(getContext(), PrefKey.IM_TOKEN, ""),
                    new RongIMClient.ConnectCallback() {
                        @Override
                        public void onTokenIncorrect() {
                            XLog.e("IM连接失败...token错误");
                        }

                        @Override
                        public void onSuccess(String s) {
                            XLog.e("IM连接成功..." + s);
                            RongIM.getInstance().refreshUserInfoCache(UserInfo(s));
                        }

                        @Override
                        public void onError(RongIMClient.ErrorCode errorCode) {
                            XLog.e("IM连接失败..." + errorCode);
                        }
                    });
        }
    }

    private UserInfo UserInfo(String user_id) {
        UserInfo userInfo = new UserInfo(user_id,
                PrefUtil.getString(getContext(), PrefKey.LOGIN_NICKNAME, ""),
                Uri.parse(PrefUtil.getString(getContext(), PrefKey.LOGIN_FACE, "")));
        XLog.e(userInfo.getUserId());
        XLog.e(userInfo.getName());
        XLog.e(userInfo.getPortraitUri());
        return userInfo;
    }

    @Override
    public void onBackPressed() {
        long cur = System.currentTimeMillis();
        if (cur - mExitTime < Constant.EXIT_INTERVAL_TIME) {
            android.os.Process.killProcess(android.os.Process.myPid());
            super.onBackPressed();
        } else {
            CommonUtil.showToast(this, getString(R.string.common_exit_two));
            mExitTime = cur;
        }
    }
}
